package cn.tedu._04weibo.controller;


import cn.tedu._04weibo.base.response.JsonResult;
import cn.tedu._04weibo.base.response.StatusCode;
import cn.tedu._04weibo.mapper.UserMapper;
import cn.tedu._04weibo.pojo.dto.UserRegParam;
import cn.tedu._04weibo.pojo.entity.User;
import cn.tedu._04weibo.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@Slf4j
@RestController
@Tag(name = "1-用户模块")
@RequestMapping("/v1/user")
public class UserController {
	@Autowired
	private UserMapper userMapper;
	@RequestMapping("/reg")
	@Operation(summary = "注册功能")
	@ApiOperationSupport(order = 10)
	public JsonResult reg(@RequestBody UserRegParam userRegParam) {
		log.debug("注册："+ userRegParam);
		
		String username = userRegParam.getUsername();
		int count = userMapper.selectByUsername(username);
		if (count > 0) {
		return new JsonResult(StatusCode.USERNAME_EXISTS);
		}
		User user = new User();
		BeanUtils.copyProperties(userRegParam, user);
		user.setCreateTime(new Date());
		log.debug("实体类:" + user);
		int i = userMapper.insertUser(user);
		if (i > 0) {
			return JsonResult.ok();
		}
		return JsonResult.ok(StatusCode.OPERATION_FAILED);
	}
	@PostMapping("/login")
	@Operation(summary = "登录功能")
	@ApiOperationSupport(order = 20)
	public JsonResult login(@RequestBody UserRegParam userRegParam, HttpSession session) {
		log.debug("登录："+ userRegParam);
		UserVO userVO = userMapper.selectByUsernameAndPassword(userRegParam);
		if (userVO == null) {
			return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
		}
		session.setAttribute("user", userVO);
		return JsonResult.ok(userVO);
	}
}
